<template>
  <div class="min-h-screen bg-[#FFFFFF] flex flex-col md:flex-row">
    <Nav></Nav>
    <div class="flex-1 p-4 md:p-8">
      <div class="max-w-3xl mx-auto">
        <!-- 顶部标题区域 -->
        <div class="flex items-center mb-4 md:mb-6">
          <el-button @click="router.back()" class="mr-2 md:mr-4 !bg-gray-50 border-none hover:!bg-gray-100">
            <el-icon><ArrowLeft /></el-icon>
          </el-button>
          <h1 class="text-xl md:text-2xl font-semibold text-gray-800">{{ isEdit ? '编辑学生' : '添加学生' }}</h1>
        </div>

        <!-- 表单卡片 -->
        <div class="bg-white rounded-xl shadow-sm p-4 md:p-8 border border-gray-100">
          <el-form :model="form" label-width="80px" md:label-width="100px" class="max-w-2xl">
            <!-- 头像上传区域 -->
            <div class="flex flex-col items-center mb-8 md:mb-12">
              <el-upload
                class="avatar-uploader mb-4 md:mb-6"
                action="#"
                :show-file-list="false"
                :auto-upload="false"
                :on-change="handleAvatarChange">
                <div class="relative group">
                  <img v-if="avatarUrl || selectedAvatar" 
                    :src="avatarUrl || selectedAvatar" 
                    class="w-24 h-24 md:w-32 md:h-32 rounded-full object-cover border-4 border-white shadow-lg">
                  <div v-else 
                    class="w-24 h-24 md:w-32 md:h-32 rounded-full bg-gray-50 border-4 border-white shadow-lg flex items-center justify-center">
                    <el-icon class="text-gray-300 text-3xl md:text-4xl"><Plus /></el-icon>
                  </div>
                  <div class="absolute inset-0 bg-black bg-opacity-40 rounded-full opacity-0 group-hover:opacity-100 flex items-center justify-center transition-opacity">
                    <span class="text-white text-xs md:text-sm">上传头像</span>
                  </div>
                </div>
              </el-upload>

              <!-- 操作按钮区域 -->
              <div v-if="selectedAvatar && !avatarUrl" class="flex gap-4 mb-4">
                <el-button 
                  type="primary"
                  class="!rounded-full"
                  @click="confirmDefaultAvatar">
                  <el-icon class="mr-1"><Check /></el-icon>
                  确认头像
                </el-button>
                <el-button 
                  class="!rounded-full" 
                  type="danger" 
                  @click="clearSelectedAvatar">
                  <el-icon class="mr-1"><Delete /></el-icon>
                  清除选择
                </el-button>
              </div>
              <!-- 默认头像选择 -->
              <div class="text-xs md:text-sm text-gray-500 mb-3 md:mb-4">上传头像或选择默认头像</div>
              <div class="flex gap-2 md:gap-4 flex-wrap justify-center">
                <img v-for="(avatar, index) in defaultAvatars" 
                  :key="index"
                  :src="avatar"
                  class="w-12 h-12 md:w-16 md:h-16 rounded-full cursor-pointer border-2 transition-all duration-300 hover:scale-125"
                  :class="selectedAvatar === avatar ? 'border-blue-500 scale-110' : 'border-transparent hover:border-gray-200'"
                  @click="selectDefaultAvatar(avatar)">
              </div>
            </div>

            <!-- 基本信息表单 -->
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4 md:gap-x-8 md:gap-y-6">
              <el-form-item label="姓名" required>
                <el-input v-model="form.username" placeholder="请输入学生姓名" class="!rounded-lg"></el-input>
              </el-form-item>

              <el-form-item label="性别" required>
                <el-radio-group v-model="form.sex">
                  <el-radio label="male" value="1">男生</el-radio>
                  <el-radio label="female" value="2">女生</el-radio>
                </el-radio-group>
              </el-form-item>

              <el-form-item label="年级" required>
                <el-select 
                  v-model="form.grade" 
                  placeholder="请选择年级" 
                  class="w-full !rounded-lg"
                  loading-text="加载中..."
                  :loading="gradersList.length === 0">
                  <el-option
                    v-for="item in gradersList"
                    :key="item.gradeName"
                    :label="item.gradeName"
                    :value="item.grade">
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="教材版本" required>
                <el-select 
                  v-model="form.version_id" 
                  placeholder="请选择教材版本" 
                  class="w-full !rounded-lg"
                  loading-text="加载中..."
                  :loading="textbooks.length === 0">
                  <el-option
                    v-for="item in textbooks"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </div>

            <!-- 提交按钮区域 -->
            <div class="flex justify-center mt-8 md:mt-12 space-x-4">
              <el-button @click="router.back()" 
                class="w-24 md:w-32 !rounded-full border-gray-300 hover:border-gray-400">
                取消
              </el-button>
              <el-button type="primary" @click="handleSubmit" 
                class="w-24 md:w-32 !rounded-full !bg-gradient-to-r from-blue-500 to-blue-600 border-none hover:from-blue-600 hover:to-blue-700">
                保存
              </el-button>
            </div>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import Nav from "@/components/nav/index.vue";
import { ref, onMounted, computed } from 'vue'; // 添加computed
import { Plus, ArrowLeft, Delete, Check } from '@element-plus/icons-vue';
import { useRouter, useRoute } from 'vue-router'; // 添加useRoute
import { ElMessage } from 'element-plus';
import { addChild, updateChild } from '@/api/student'; // 添加updateChild和getChildDetail
import { getTextbooks, getGradesList } from '@/api/common';
import upload from '@/utils/upload';
import { setUserInfo, clearUserInfo,getUserInfo } from '@/utils/auth'
import { userApi } from '@/api'

const router = useRouter();
const route = useRoute(); // 获取路由对象
const avatarUrl = ref('');
const gradersList = ref([]);
// 添加selectedAvatar响应式变量
const selectedAvatar = ref('');
const imgUrl = import.meta.env.VITE_IMG_BASE_URL;

const loading = ref(false); // 添加loading状态

// 判断是否为编辑模式
const studentId = route.query.id;
const isEdit = computed(() => !!studentId);

const form = ref({
  username: '',
  sex: '1',
  grade: '',
  version_id: '',
  avatar_url: ''
});


// 默认头像列表
const defaultAvatars = [
  new URL('@/assets/images/avatar/10001.png', import.meta.url).href,
  new URL('@/assets/images/avatar/10002.png', import.meta.url).href,
  new URL('@/assets/images/avatar/10003.png', import.meta.url).href,
  new URL('@/assets/images/avatar/10004.png', import.meta.url).href,
  new URL('@/assets/images/avatar/10005.png', import.meta.url).href,
  new URL('@/assets/images/avatar/10006.png', import.meta.url).href,
  new URL('@/assets/images/avatar/10007.png', import.meta.url).href,
  new URL('@/assets/images/avatar/10008.png', import.meta.url).href,
  new URL('@/assets/images/avatar/10009.png', import.meta.url).href,
  new URL('@/assets/images/avatar/10010.png', import.meta.url).href,
];

const handGrandersList = async () => {
  try {
    const res = await getGradesList();
    return gradersList.value = res;
  } catch (error) {
    ElMessage.error('获取年级失败');
  }
};

// 修改确认默认头像的方法
const confirmDefaultAvatar = async () => {
  if (selectedAvatar.value) {
    try {
      // 将URL转换为文件对象
      const response = await fetch(selectedAvatar.value);
      const blob = await response.blob();
      const file = new File([blob], 'avatar.png', { type: blob.type });
      // 这里调用上传接口，假设upload.upload方法可以处理URL
      const url = await upload.upload(file, 'image');

      avatarUrl.value = imgUrl+url;
      form.value.avatar_url = url;
      // 移除这行，不再清空selectedAvatar
      // selectedAvatar.value = ''; 
      ElMessage.success('头像设置成功');
      } catch (error) {
      ElMessage.error('头像设置失败');
    }
  }
};

// 添加清除选择的方法
const clearSelectedAvatar = () => {
  selectedAvatar.value = '';
};

const handleAvatarChange = async (file) => {
  try {
    // 如果是默认头像(字符串路径)，直接使用
    if (typeof file === 'string') {
      avatarUrl.value = file;
      form.value.avatar = file;
    } 
    // 如果是上传的文件
    else {
      // 显示预览
      avatarUrl.value = URL.createObjectURL(file.raw);
      
      // 调用上传接口并打印完整响应
      const response = await upload.upload(file.raw, 'image');

      // 判断response类型并获取url
      const url = typeof response === 'string' ? response : response?.url;

      avatarUrl.value = imgUrl+url;
      form.value.avatar_url = url;
    }
  } catch (error) {
    console.error('头像上传失败:', error);
    ElMessage.error('头像设置失败');
    avatarUrl.value = '';
    form.value.avatar = '';
  }
};


const handleSubmit = async () => {
  if (!form.value.username || !form.value.grade || !form.value.version_id) {
    ElMessage.warning('请填写必填项');
    return;
  }

  if (!form.value.avatar_url) {
    ElMessage.warning('请上传头像或选择默认头像');
    return;
  }

  try {
    loading.value = true;
    
    if (isEdit.value) {
      // 编辑模式，调用更新API
      await updateChild({
        ...form.value,
        id: studentId
      });
      ElMessage.success('更新成功');
    } else {
      // 添加模式
      await addChild(form.value);
      ElMessage.success('添加成功');
    }

    // 先获取新用户信息
    const userInfo = await userApi.getUserInfo()
    // 清理旧用户信息
    clearUserInfo()
    // 保存新用户信息
    setUserInfo(userInfo)

    // 这里添加实际的提交逻辑
    ElMessage.success('添加成功');
    router.back();
  } catch (error) {
    ElMessage.error('操作失败，请重试');
  }
};

const selectDefaultAvatar = (avatar) => {
  selectedAvatar.value = avatar; // 设置selectedAvatar
  
  // 如果是编辑模式，需要同时更新展示图片
  if (isEdit.value) {
    // 清除原有头像URL，让模板使用selectedAvatar作为展示
    avatarUrl.value = '';
        avatarUrl.value = '';
        form.value.avatar_url = '';
  }
};

const clearAvatar = () => {
  avatarUrl.value = '';
  selectedAvatar.value = '';
  form.value.avatar_url = '';
};

// 年级和教材版本列表
// const grades = ref([]);
// 教材版本列表
const textbooks = ref([]);


// 获取教材版本数据
const fetchTextbooks = async () => {
  try {
    const res = await getTextbooks();
    return textbooks.value = res.map(item => ({
      label: item.versionName,
      value: item.versionId
    }));
  } catch (error) {
    ElMessage.error('获取教材版本失败');
  }
};

// 获取学生详情
const getStudentDetail = async () => {
  if (!studentId) return;
  
  try {
    loading.value = true;
    // 这里假设有一个获取学生详情的API
    // 如果没有，可以从用户信息中获取
    const userInfo = getUserInfo();
    const student = userInfo.children.find(child => child.id == studentId);
    
    if (student) {
      form.value = {
        id: student.id,
        username: student.username,
        sex: student.sex.toString(),
        grade: student.grade,
        version_id: student.version_id,
        avatar_url: student.avatar_url
      };
      
      // 设置头像
      if (student.avatar_url) {
        avatarUrl.value = imgUrl + student.avatar_url;
      }
    }
  } catch (error) {
    console.error('获取学生信息失败:', error);
    ElMessage.error('获取学生信息失败');
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  handGrandersList();
  fetchTextbooks(); // 新增教材版本获取

  // 如果是编辑模式，获取学生详情
  if (isEdit.value) {
    getStudentDetail();
  }
});
</script>

<style scoped>
/* 添加移动端样式 */
@media (max-width: 768px) {
  :deep(.el-form-item__label) {
    padding-bottom: 4px;
  }
  
  :deep(.el-form-item) {
    margin-bottom: 16px;
  }
}

/* 保持原有样式 */
.avatar-uploader :deep(.el-upload) {
  cursor: pointer;
}

:deep(.el-input__wrapper),
:deep(.el-select .el-input__wrapper) {
  box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.1) !important;
}

:deep(.el-input__wrapper:hover),
:deep(.el-select .el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.2) !important;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

.bg-white {
  transition: box-shadow 0.3s ease;
}

.bg-white:hover {
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}
</style>